﻿CREATE PROCEDURE [dbo].[usp_select_FaultsToQueue]
(
	@BatchSize	int
   ,@Debug      bit             = 0
)
AS

SET NOCOUNT ON;

-- Bootstrap
DECLARE @DebugPrefix       varchar(10)
DECLARE @ErrorCode         int

SET @ErrorCode          = 0;
SET @DebugPrefix        = '>>> DEBUG: '

-- Print parameters
IF (@Debug > 0)
BEGIN
   PRINT @DebugPrefix + 'usp_select_Fault_To_Queue stored procedure execution started...'
END;
DECLARE @Statement nvarchar(4000)
SET @Statement = N'SELECT TOP ' + CONVERT(varchar, @BatchSize) + '
   f.[FaultID]
  ,f.[Application]
  ,f.[Description]
  ,f.[ErrorType]
  ,f.[FailureCategory]
  ,f.[FaultCode]
  ,f.[FaultDescription]
  ,f.[FaultSeverity]
  ,f.[Scope]
  ,f.[ServiceInstanceID]
  ,f.[ServiceName]
  ,f.[FaultGenerator]
  ,f.[MachineName]
  ,f.[DateTime]
  ,f.[ExceptionMessage]
  ,f.[ExceptionType]
  ,f.[ExceptionSource]
  ,f.[ExceptionTargetSite]
  ,f.[ExceptionStackTrace]
  ,f.[InnerExceptionMessage]
  ,f.[InsertedDate]
	
FROM dbo.Fault f 
LEFT OUTER JOIN dbo.ProcessedFault pf ON pf.ProcessedFaultID = f.FaultID
WHERE 
		 pf.ProcessedFaultID IS NULL;'

EXECUTE sp_executesql @Statement

-- CHECK FOR ERROR
SET @ErrorCode = @@Error;
IF (@ErrorCode <> 0) GOTO ERROR_HANDLER;
			
RETURN 0;

-- Handles errors.
ERROR_HANDLER:
IF (@ErrorCode <> 0)
BEGIN
    IF (@Debug > 0) 
		BEGIN
			PRINT @DebugPrefix + 'Error Code = ' + CAST(@ErrorCode AS varchar(10)) + ' occurred.';
			RETURN @ErrorCode
		END

    -- Don't return any evidence of what specific error occurred, i.e. 
    -- we want to ward off potential hackers.
    RETURN 1;
END;

SET NOCOUNT OFF;
